<%@ page language="java" pageEncoding="UTF-8" import="ll.sms.pojo.ChannelCombox,ll.sms.util.*"%>
<%@page import="java.util.List;"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>代理信息修改</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
		<link rel="stylesheet" type="text/css" href="../ext/ext-all.css" />
		<link rel="stylesheet" type="text/css" href="../ext/sms.css" />
		<script type="text/javascript" src="../ext/ext-base.js"></script>
		<script type="text/javascript" src="../ext/ext-all.js"></script>


<%

List<ChannelCombox> list = SmsUtil.getChannelList();



%>
<script type="text/javascript">
Ext.BLANK_IMAGE_URL = '../images/s.gif';
</script>

	<script type="text/javascript">
	/*
	function cellclick(grid, rowIndex, columnIndex, e) {
    var record = grid.getStore().getAt(rowIndex);   //Get the Record
    var fieldName = grid.getColumnModel().getDataIndex(columnIndex); //Get field name
    var data = record.get(fieldName);
    Ext.MessageBox.alert('show','当前选中的数据是'+data);
	}
	*/

	Ext.apply(Ext.form.VTypes, {
	password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },

    passwordText : '密码不匹配'
	});
	Ext.onReady(function(){

	var swin;//弹出window对象


    var wi = 600;
//****************************************************************
//****************************************************************
//****************************************************************
var firstGrid;
var secondGrid;
var displayPanel;
var firstGridStore;
var secondGridStore;
var fields = [
	   {name: 'name', mapping : 'name'},
	   {name: 'defaultname', mapping : 'defaultname'},
	   {name: 'userdname', mapping : 'userdname'}
	];

var cols = [
		{header: "服务器名", width: 160, sortable: true, dataIndex: 'userdname'},
		{header: "服务器默认名", width: 160, sortable: true, dataIndex: 'defaultname'},
		{ id : 'name', header: "服务器ID", width: 10, sortable: true, dataIndex: 'name'}
	];

function creatorOneGrid(){
var myData = {records : [{'name':'12234234324','defaultname':'dfaultname','userdname':'unameooo'}]};
  firstGridStore = new Ext.data.JsonStore({
        fields : fields,
		data   : myData,
		root   : 'records'
    });

        firstGrid = new Ext.grid.GridPanel({
		ddGroup          : 'secondGridDDGroup',
        store            : firstGridStore,
        columns          : cols,
		enableDragDrop   : true,
        stripeRows       : true,
        autoExpandColumn : 'name',
        width            : wi/2,
		region           : 'west',
        title            : '未授权通道'
    });

    return firstGrid;
}

function creatorTwoGrid(){
var myData1 = {records : []};
 secondGridStore = new Ext.data.JsonStore({
        fields : fields,
        data   : myData1,
		root   : 'records'
    });

     secondGrid = new Ext.grid.GridPanel({
		ddGroup          : 'firstGridDDGroup',
        store            : secondGridStore,
        columns          : cols,
		enableDragDrop   : true,
        stripeRows       : true,
        autoExpandColumn : 'name',
        width            : wi/2,
		region           : 'center',
        title            : '已授权通道'
    });

    return secondGrid;
}

function creatorWindowView(){
 displayPanel = new Ext.Window({
		title    : '通道配置',
		width    : wi,
		height   : 400,
		layout   : 'border',
		applyTo : 'panel123',
		closeAction :'close',
		items    : [
			firstGrid,
			secondGrid
		]
		,
		bbar    : [
			{
				text    : '重置所有',
				handler : function() {
					firstGridStore.loadData(myData);
					secondGridStore.loadData(myData1);
				}
			},'-',
			{
				text    : '关闭',
				handler : function() {
					displayPanel.close();
				}
			}
			,'->',
			{
			text    : '确定',
			handler : function() {
					doset();
				}
			}

		]
	});


	var blankRecord =  Ext.data.Record.create(fields);

	/****
	* Setup Drop Targets
	***/
	// This will make sure we only drop to the view container
	var firstGridDropTargetEl =  firstGrid.getView().el.dom.childNodes[0].childNodes[1];
	var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
		ddGroup    : 'firstGridDDGroup',
		copy       : true,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = firstGridStore.find('name', record.data.name);
				// if not found
				if (foundItem  == -1) {
					firstGridStore.add(record);

					// Call a sort dynamically
					firstGridStore.sort('name', 'ASC');

					//Remove Record from the source
					ddSource.grid.store.remove(record);
				}
			}

			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});


	// This will make sure we only drop to the view container
	var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1]

	var destGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
		ddGroup    : 'secondGridDDGroup',
		copy       : false,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = secondGridStore.find('name', record.data.name);
				// if not found
				if (foundItem  == -1) {
					secondGridStore.add(record);
					// Call a sort dynamically
					secondGridStore.sort('name', 'ASC');

					//Remove Record from the source
					ddSource.grid.store.remove(record);
				}
			}
			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});


	return displayPanel;

}


	// used to add records to the destination stores
	function getmaodieview(){
		var isForm = new Ext.form.FormPanel({
        //title: 'ItemSelector Test',
        //width:700,
        //regin
        bodyStyle: 'padding:10px;',
        //renderTo: 'itemselector',
        items:[{
            xtype:"itemselector",
            name:"itemselector",
            fieldLabel:"为该代理配置通道",
            dataFields:["code", "desc"],
            toData:[],
            msWidth:250,
            msHeight:200,
            valueField:"code",
            displayField:"desc",
            imagePath:"../images/",
            toLegend:"已配置通道",
            fromLegend:"未配置通道",
            fromData:[['aaaaa','bbbbbb']],
            toTBar:[{
                text:"重置",
                handler:function(){
                    var i=isForm.getForm().findField("itemselector");
                    i.reset.call(i);
                }
            }]
        }],

        buttons: [{
            text: '确定',
            handler: function(){
                if(isForm.getForm().isValid()){
                   doset(isForm.getForm().getValues(true));
                }
            }
        }]
    });
	return new Ext.Window({
	    title    : '通道配置',
		width    : 800,
		height   : 400,
		layout   : 'fit',
		//applyTo : 'panel123',
		closeAction :'close',
		items    : [
			isForm
		]
	});

	}

	var showproxy;
	function creatorshowproxy(){
	showproxy =new Ext.Button({
	        // applyTo:'login-button-group',
	         text: '配置代理',

	         handler: function()
		         {
		         	creatorOneGrid();
		         	creatorTwoGrid();
		         	creatorWindowView();
					displayPanel.show();
		         }
		     	});
		     	return showproxy;
		}
//****************************************************************
//****************************************************************
//****************************************************************
	var store1 = new Ext.data.SimpleStore({
	fields: ['clazz', 'showname'],
	data : <%=ExtJsonBuilder.channel2ArrayStringNoAll(list)%>
	});

	var simple;

    var comb = new Ext.form.ComboBox({
            emptyText : '请选择',
            store: store1,
            mode:'local',
            triggerAction:'all',
            valueField: 'clazz',
            name:'_adefaultchannel_',
            id:'_adefaultchannel_',
            hiddenName : 'adefaultchannel_',
            displayField:'showname',
 			fieldLabel: '重选通道',
 			 width : 120
            });

		var thisgrid;
	//---定义修改form

	function creatorSimpleForm(){
	    creatorshowproxy();
		simple = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/proxyeditor.jsp',
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',
        items: [
           {
                fieldLabel: '管理员用户名',
                name: 'auname',
                vtype:'alphanum',
                vtypeText:'用户名只能包括字母或者数字',
                allowBlank:false,

                blankText :'管理员用户名必须填写'
            },{
                fieldLabel: '密码',
                name: 'apwd',
                vtype:'alphanum',
               //inputType : 'password',
                vtypeText:'密码只能包括字母或者数字',
                allowBlank:false,
                id:'apwd',
                blankText :'密码必须填写'
            },{
                fieldLabel: '重新输入密码',
                name: 'reapwd',
                vtype:'alphanum',
                //inputType : 'password',
                vtypeText:'密码只能包括字母或者数字',
                allowBlank:false,
                initialPassField: 'apwd',
                blankText :'密码必须填写'

            },{
                fieldLabel: '代理公司名',
                name: 'acompany',
                allowBlank:false,
                blankText :'代理公司名必须填写'
            },{
                fieldLabel: '公司地址',
                name: 'aaddress'
            },{
                fieldLabel: '公司电话',
                name: 'aphone'
            },{
                fieldLabel: '联系人',
                name: 'alinkman',
                allowBlank:false,
                blankText :'联系人必须填写'
            },{
                fieldLabel: '联系人电话',
                name: 'alinkmanphone',
                allowBlank:false,
                blankText :'联系人电话必须填写'
            },{
                fieldLabel: '联系人QQ',
                name: 'alinkmanqq'
            },
            {
                fieldLabel: '可发短信数',
                name: 'asmsnum',
                xtype:'numberfield',
                allowBlank:false,
                blankText :'可发短信数必须填写'
            },{
                fieldLabel: '是否可用',
                name: 'aavailable',
                xtype:'hidden'
            },{
                fieldLabel: '已配置代理',
                name: 'adefaultchannel',
                id : 'adefaultchannel',
                xtype:'hidden'
            },showproxy
            ],
            buttons: [{
            text: '修改',
            handler : function(){
            //alert(Ext.get('checkbox').getValue());

           	var v = simple.getForm().findField('adefaultchannel').getValue();
			if(Ext.isEmpty(v)){
			Ext.MessageBox.confirm('警告', '你没有对代理配置通道，你确定不配置通道?',dosetchannel);
			}else{
			dosubmit();
			}

			function dosetchannel(btn){
				if(btn=='yes'){
					dosubmit();
				}else{
					displayPanel.show();
				}
			}

			function dosubmit(){
			 simple.form.submit({

					waitMsg : '正在处理......',
					success : function(form, action) {
            	        simple.form.reset();
						Ext.Msg.alert('成功',action.result.msg);
					},
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);
							}else{
							Ext.MessageBox.alert('错误','--------非法输入-------');
							}
					}
				});
			}

            }
        }]
    });
    return simple;
	}

    //form end
//aaddress,aphone,alinkman,alinkmanphone,alinkmanqq
	var AdminRecord = Ext.data.Record.create([
        {name: 'aid', type: 'string'},
        {name: 'auname', type: 'string'},
        {name: 'apwd', type: 'string'},
        {name: 'acompany', type: 'string'},
        {name: 'aregisttime', type: 'string'},
        {name: 'arank', type: 'int'},
        {name: 'asmsnum', type: 'int'},
        {name: 'aavailable', type: 'int'},
            {name: 'aaddress', type: 'string'},
            {name: 'aphone', type: 'string'},
            {name: 'alinkman', type: 'string'},
            {name: 'alinkmanphone', type: 'string'},
            {name: 'alinkmanqq', type: 'string'},
            {name: 'adefaultchannel', type: 'string'}

    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/proxtlist.jsp'}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },AdminRecord),
        remoteSort: true
    });

    function avi(value){
		if(value==0){
			return '是';
			}else if(value==-1){
			return '否';
			}else{
			return 'N/A';
			}
        }

    var columns = new Ext.grid.ColumnModel([
        //{header: '编号', dataIndex: 'aid',width:1},
        new Ext.grid.RowNumberer(),
        {header:'充值记录',dataIndex:"chargelist",width:70,align:'center',renderer:cbutton},
        {header: '用户名', dataIndex: 'auname',renderer:aunames},
        {header: '公司名称', dataIndex: 'acompany'},
        //{header: '注册日期', dataIndex: 'aregisttime'},
        {header: '可用余额', dataIndex: 'asmsnum'},
        {header: '充值',dataIndex:"chargeme",width:70,align:'center',renderer:cmbutton},
        {header: '修改密码',dataIndex:"changepwd",width:70,align:'center',renderer:cpbutton}
    ]);

	function aunames(value,c){
		return "<font style='color:red;text-decoration:underline;cursor:hand;font-color:red;'>"+value+"</font>";
	}
	function cbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>充值记录</button>";
	  return returnStr;
	}

	function cmbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>充值</button>";
	  return returnStr;
	}

	function cpbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>修改密码</button>";
	  return returnStr;
	}

//=充值
function getchargeForm(chargeedId,chargedUsername){
	var chargefield=new Ext.form.NumberField({
				fieldLabel: '充值金额',
                name: 'addcharge',
                width : '80%',
                id:'addcharge',
                xtype :'NumberField',
                allowBlank:false,
                blankText :'金额必须填写'
				});

var chargeform = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/charge.jsp?opflag=a&chargeedId='+chargeedId+'&chargedUsername='+chargedUsername,
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',

        items: [
            chargefield
            ],
            buttons: [{
            text: '充值',
            handler : function(){chargeform.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {
					   doreset();
						Ext.Msg.alert('成功',action.result.msg);
					}
					,
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);}else{
							Ext.MessageBox.alert('错误','---------非法输入---------');
							}
					}
				});
            }
        }]
            });
            return chargeform;
}

//*************

function getchangepwdForm(userid){
var pwdform = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/proxyeditor.jsp?flag=changepassword&userid='+userid,
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',

        items: [

             {
                fieldLabel: '新密码',
                width : '80%',
                name :'pwd',
                allowBlank:false,
                blankText :'密码必须填写'
            },{
                fieldLabel: '重复新密码',
                width : '80%',
                 name :'npwd',
                allowBlank:false,
                blankText :'密码必须填写'
            }

            ],
            buttons: [{
            text: '修改',
            handler : function(){pwdform.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {

						Ext.Msg.alert('成功',action.result.msg);
					}
					,
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);}else{
							Ext.MessageBox.alert('错误','---------非法输入---------');
							}
					}
				});
            }
        }]
            });
       return pwdform;
}

//*************************
//获得充值列表
function getChargeListGrid(pid){

var ChargeRecord = Ext.data.Record.create([
        {name: 'cid', type: 'string'},
        {name: 'cuname', type: 'string'},
        {name: 'cprice', type: 'string'},
        {name: 'csmsnum', type: 'string'},
        {name: 'ctime', type: 'string'},
        {name: 'coperator', type: 'string'},
        {name: 'cnote', type: 'string'}


    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/chargelist.jsp?pid='+pid}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },ChargeRecord),
        remoteSort: true
    });


    var columns = new Ext.grid.ColumnModel([
        //{header: '编号', dataIndex: 'aid',width:1},
        new Ext.grid.RowNumberer(),
        //{header: '被充值者', dataIndex: 'cuname'},
        {header: '充值', dataIndex: 'csmsnum'},
        {header: '充值时间', dataIndex: 'ctime'},
        {header: '操作员', dataIndex: 'coperator'}
        //{header: '通道密码', dataIndex: 'hpwd'}
    ]);

        columns.defaultSortable = true;
        var grid = new Ext.grid.GridPanel({
        loadMask: true,
        store: store,
        cm: columns,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg:'没有记录'

        })
    });

    store.load({params:{start:0,limit:15}});

    return grid;

}

function showmywindow(obj,t,w,h){
	var tw;
	var th;

	if(w==undefined){
		tw = 500;
	}else{
		tw = w;
	}
	if(h==undefined){
		th = 300;
	}else{
		th = h;
	}

	var swin = new Ext.Window({
		title : t,
		width    : tw,
		height   : th,
		layout   : 'fit',
		//applyTo : 'panel123',
		closeAction :'close',
		items    : [obj],
		bbar    : [
			'->',
			{
			text    : '关闭',
			handler : function() {

					swin.close();
					if(t=='信息修改'){
					//作孽啊 没的办法
					 window.location.reload();
					}
				}
			}

		]
	});
	return swin;
	}


    columns.defaultSortable = true;

  var _grid_ = new Ext.grid.GridPanel({
        title: '代理注册列表',
        region: 'center',
        loadMask: true,
        store: store,
        cm: columns,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg:'没有记录'

        })
    });

    store.load({params:{start:0,limit:15}});
    /*
    grid.on('rowclick',function (grid,rowIndex,event){
    var record = grid.getStore().getAt(rowIndex);
   	simple.getForm().loadRecord(record);
    });
   */
	thisgrid =_grid_;

    _grid_.on('cellclick',function (ngrid, rowIndex, columnIndex, e){
    var record = ngrid.getStore().getAt(rowIndex);   //Get the Record
    var fieldName = ngrid.getColumnModel().getDataIndex(columnIndex); //Get field name

   	if(fieldName == 'auname'){
   	var w = showmywindow(creatorSimpleForm(),'信息修改',500,400);
   	w.show();
	simple.getForm().loadRecord(record);
   	}

   	if(fieldName == 'chargelist'){

   	var w =showmywindow(getChargeListGrid(record.get('auname')),record.get('acompany')+'充值历史');
   	w.show();
   	}

   	if(fieldName == 'chargeme'){
   	var w =showmywindow(getchargeForm(record.get('aid'),record.get('auname')),'充值',300,150);
   	w.show();
   	}

   	if(fieldName == 'changepwd'){
   	var w =showmywindow(getchangepwdForm(record.get('aid')),'更改密码',300,200);
   	w.show();
   	}
    //var data = record.get('aid');
    //alert(data);
    //Ext.MessageBox.alert('show','当前选中的数据是'+data);
    });

	var viewport = new Ext.Viewport({
	renderTo:'mt',
	layout:'border',
	items:[
	_grid_,
	//simple,
	{region:'south',contentEl:'inp',heigth:40}
	//{region:'east',html:'east',width:'30%'}
	]
	});



	function deleteProxy(){
	   Ext.MessageBox.confirm('提示框', '您确定要进行该操作？', function(btn){
                if (btn == 'yes') {
                 var aidvalue = Ext.getCmp('aid').getValue();
                 if(aidvalue == ''){
                 	Ext.Msg.alert('警告','你未选择任何记录进行删除！');
                 	return;
                 }
                 Ext.Ajax.request({
                  url : '../ajaxjsp/delete.jsp',
                  method : 'POST',
                  params : {
                      tablename : 'sms_admin',
                      id :aidvalue
                  },

                     success: function(response, options) {
                        //获取响应的json字符串
                       var responseArray = Ext.util.JSON.decode(response.responseText);
                            if(responseArray.success==true){
								//Ext.Msg.alert('成功',responseArray.msg);
								simple.form.reset();
								grid.store.reload();
                            }
                            else{
                                Ext.Msg.alert('失败',responseArray.msg);
                            }
                         }


              });
                }
            });
	}


    function doset(){
	var store = secondGrid.getStore();
	var count = store.getCount();
	var value='';
	for(var i = 0 ; i<count ;i++){
		value = value + store.getAt(i).get('name');
		if(i!=count-1){
		value = value+',';
		}
	}
	simple.getForm().findField('adefaultchannel').setValue(value);
	displayPanel.close();
	}

	function doreset(){

		//_grid_.getStroe().reload();
	}

});
	</script>
  </head>

  <body>
   <div id="mt"></div>
   <div id="north1"></div>
   <div id="south"></div>

   <div id = "panel123"></div>

   <div id="chargelist"></div>
   <div id="chargeme"></div>
   <div id="changepwd"></div>
   <div id="wait" align="center"></div>
   <input id="inp" value="刷新页面" type="button" onclick="javascript:window.location.reload();"></input>
  </body>
</html>
